<template>
    <Teleport to="body">
        <transition name="el-fade-in">
            <div class="dialogue-dialog" v-if="visible">
                <div class="dialogue-dialog__content">
                    <div class="dialogue-header">
                        <div class="title">和{{ receiveInfo.user.nickname }}的对话</div>

                        <img class="icon-close" :src="_oss_ + 'images/icon-close-default.png'" @click="onClose" />
                    </div>

                    <div class="dialogue-body" ref="dialogueBodyRef">
                        <template v-for="item in receiveInfo.history" :key="item.id">
                            <div class="receive-item" v-if="item.send_id != userStore.userInfo.id">
                                <div class="avatar" @click="GoToPageHome(item.send_id)">
                                    <img :src="receiveInfo.user.avatar ||
                                        _defaultAvatar_
                                        " />
                                </div>

                                <div class="message" v-html="formatComment(item.message)"></div>

                                <div class="time">{{ handlerDate(item.createtime) }}</div>
                            </div>

                            <div class="send-item" v-if="item.send_id == userStore.userInfo.id">
                                <div class="time">{{ handlerDate(item.createtime) }}</div>
                                <div class="message" v-html="formatComment(item.message)"></div>
                                <div class="avatar">
                                    <img :src="userStore.avatar ||
                                        _defaultAvatar_
                                        " />
                                </div>
                            </div>
                        </template>
                    </div>
                    <div class="dialogue-footer">
                        <div class="comment-box">
                            <img class="avatar" :src="userStore.avatar || _defaultAvatar_" />

                            <div class="comment-box__right">
                                <el-input v-model="comment" type="textarea" class="comment-input" resize="none"
                                    :autosize="{ minRows: 4, maxRows: 4 }" maxlength="1000"></el-input>

                                <div class="tools">
                                    <EmojiPickerP @select-emoji="onSelectEmoji" />

                                    <div class="btn-group">
                                        <el-button onfocus="this.blur()" type="primary" @click="onSend"
                                            :loading="isSendLoading">
                                            回复
                                        </el-button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </transition>
    </Teleport>
</template>
<script setup>
import { GetDialogueUserInfo, SendDialogueMessage } from "@/api";
import emojiList from "@/config/emoji.js";

const userStore = useUserStore();
const visible = ref(false);
const receiveId = ref(null);
const receiveInfo = ref(null);
const comment = ref("");
const isSendLoading = ref(false);
const dialogueBodyRef = ref(null);
let eventSource = null;

const onSelectEmoji = (name) => {
    comment.value += `[${name}]`;
}

const onScrollBottom = () => {
    dialogueBodyRef.value.scrollTop = dialogueBodyRef.value.scrollHeight;
}

const initSSE = () => {
    eventSource = new EventSource('https://marketing.vrnewg.com/v1/dialogue/stream?send_id=' + userStore.userInfo.id + '&receive_id=' + receiveId.value);

    // 监听消息事件
    eventSource.onmessage = (event) => {
        const data = JSON.parse(event.data);
        receiveInfo.value.history.push(...data);
        onScrollBottom();
    };

    // 连接成功事件
    eventSource.onopen = (event) => {
        console.log('连接已建立');
    };

    // 错误处理
    eventSource.onerror = (error) => {
        console.error('EventSource 发生错误:', error);
        eventSource.close(); // 手动关闭连接
        initSSE(); // 重新连接
    };
}

const onSend = async (e) => {
    e.preventDefault();
    if (comment.value.length) {
        const res = await SendDialogueMessage({
            receive_id: receiveId.value,
            message: comment.value
        });

        if (res.code == 200) {
            // 加入history
            receiveInfo.value.history.push(res.data)
            comment.value = "";
            await nextTick();
            onScrollBottom();
        } else {
            Message().error("网络错误");
        }
    }
}

const onClose = () => {
    receiveId.value = null;
    receiveInfo.value = null;
    comment.value = "";
    visible.value = false;
    eventSource.close();
}

const formatComment = (commentStr) => {
    for (let emoji of emojiList) {
        const reg = new RegExp(`\\[${emoji}\\]`, "g");
        commentStr = commentStr.replace(
            reg,
            `<img emoji-icon src='${_oss_}images/emoji/${emoji}.gif' />`
        );
    }
    return commentStr;
};

defineExpose({
    open(receive_id) {
        GetDialogueUserInfo({ receive_id }).then(async (res) => {
            receiveInfo.value = res.data;
            receiveId.value = receive_id;
            visible.value = true;
            await nextTick();

            onScrollBottom();
            initSSE();
        })
    },
    close() {
        onClose();
    }
})
</script>
<style lang="scss" scoped>
.dialogue-dialog {
    position: fixed;
    left: 0;
    top: 0;
    width: 100vw;
    height: 100vh;
    z-index: 999;

    &__content {
        position: absolute;
        top: 50%;
        left: 50%;
        width: 936px;
        height: 688px;
        transform: translate(-50%, -50%);
        border-radius: 20px;
        background: #fff;

        .dialogue-header {
            position: relative;
            height: 65px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 39px;

            &::after {
                position: absolute;
                bottom: 0;
                left: 50%;
                width: calc(100% - 60px);
                content: "";
                border-top: 1px solid #F1F1F1;
                transform: translateX(-50%);
            }

            .title {
                font-weight: bold;
                font-size: 18px;
                color: #333333;
            }

            .icon-close {
                width: 17px;
                height: 17px;
                display: block;
                cursor: pointer;
            }
        }

        .dialogue-body {
            height: calc(100% - 65px - 175px);
            overflow: auto;
            padding: 20px 39px 0;

            .receive-item,
            .send-item {
                display: flex;
                margin-bottom: 20px;
            }

            .avatar {
                width: 42px;
                height: 42px;
                border-radius: 50%;
                overflow: hidden;
                cursor: pointer;

                img {
                    width: 100%;
                    height: 100%;
                    object-fit: cover;
                }
            }

            .time {
                font-size: 12px;
                color: #999;
            }

            .message {
                position: relative;
                max-width: 348px;
                padding: 10px;
                border-radius: 8px;
                line-height: 20px;
                word-wrap: break-word;
                word-break: break-all;

                :deep(img[emoji-icon]) {
                    width: 20px;
                    vertical-align: top;
                }

                &::after {
                    content: "";
                    position: absolute;
                    width: 0;
                    height: 0;
                    border: 5px solid;
                    transform: rotate(45deg);
                }
            }

            .receive-item {

                .message {
                    background: #F4F4F4;
                    color: #000;
                    font-size: 14px;
                    margin-left: 15px;

                    &::after {
                        left: -5px;
                        top: 16px;
                        border-color: transparent transparent #F4F4F4 #F4F4F4;
                    }
                }

                .time {
                    margin-left: 8px;
                }
            }

            .send-item {
                justify-content: flex-end;

                .message {
                    font-size: 14px;
                    color: #FFFFFF;
                    background-color: #5085FB;
                    margin-right: 15px;

                    &::after {
                        right: -5px;
                        top: 16px;
                        border-color: #5085FB #5085FB transparent transparent;
                    }
                }

                .time {
                    padding-right: 8px;
                }
            }
        }

        .dialogue-footer {
            position: relative;
            height: 175px;
            padding: 16px 30px 0;

            &::after {
                position: absolute;
                top: 0;
                left: 50%;
                width: calc(100% - 60px);
                content: "";
                border-top: 1px solid #F1F1F1;
                transform: translateX(-50%);
            }

            .comment-box {
                display: flex;

                .avatar {
                    width: 42px;
                    height: 42px;
                    border-radius: 50%;
                    margin-right: 15px;
                }

                &__right {
                    width: 100%;

                    .tools {
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                        margin-top: 13px;
                    }
                }
            }
        }
    }
}
</style>